﻿/*
 * QtPet Online File Manager v1.0
 * Copyright (c) 2009, Zhifeng Lin (fszlin[at]gmail.com)
 * 
 * Licensed under the MS-PL license.
 * http://qtfile.codeplex.com/license
 */

using System;
using System.IO;
using System.Text;

namespace QtFile.FileBased
{
	public abstract class FileBasedService
	{
		private readonly string rootPath;

		private readonly string username;

		private RootFolder rootFolder;

		private readonly bool encodeUsername;

		private readonly char directorySeparator;

		protected RootFolder RootFolder
		{
			get
			{
				if (rootFolder == null)
					rootFolder = new RootFolder(rootPath, username, encodeUsername, directorySeparator);
				return rootFolder;
			}
		}

		protected string RootPath
		{
			get { return rootPath; }
		}

		public FileBasedService(string rootPath, string username, bool encodeUsername, char directorySeparator)
        {
			Helper.ValidateNotNullOrEmpty(rootPath, "rootPath");
			Helper.ValidateNotNullOrEmpty(username, "username");

            this.rootPath = rootPath;
			this.username = username;

			if (!Directory.Exists(rootPath))
				Directory.CreateDirectory(rootPath);

			this.encodeUsername = encodeUsername;
			this.directorySeparator = directorySeparator;
		}

		protected string ResolvePathResult(string path)
		{
			if (Path.IsPathRooted(path))
				path = path.Substring(RootFolder.RootPath.Length + 1);

			StringBuilder builder = new StringBuilder(path.Length);
			foreach (var c in path)
			{
				if (c == Path.DirectorySeparatorChar || c == Path.AltDirectorySeparatorChar)
					builder.Append(directorySeparator);
				else
					builder.Append(c);
			}
			return builder.ToString();
		}

		public long GetSize()
		{
			return RootFolder.GetSize();
		}
	}
}
